<template>
  <div id="container"></div>
</template>

<script setup>
import { onMounted } from 'vue';
import * as Cesium from 'cesium';
import './Widgets/widgets.css';

// 设置cesium 静态资源路径
window.CESIUM_BASE_URL = '/';

// 天地图 官网申请的key https://console.tianditu.gov.cn/api/key
const webKey = '01fc395160d8eb3b82aefe65b2280e58';

Cesium.Ion.defaultAccessToken =
  'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJmNDkwYWVhOS0wNzI5LTQ3OTEtOWFiMC1kY2M3MTFiM2I2NWQiLCJpZCI6MTkyNTU1LCJpYXQiOjE3MDY1MTM0MTh9.YAPVHr1d7PBuWayCXM9deCxKg3AbtsXUJiVpubVS3NY';

// https://cesium.com/learn/cesiumjs/ref-doc/SampledPositionProperty.html?classFilter=sam
// new Cesium.SampledPositionProperty(referenceFrame, numberOfDerivatives)

onMounted(async () => {
  // 地球视图，底图加载
  const viewer = new Cesium.Viewer('container', {
    //信息窗口
    infoBox: true, // 可查看某个建筑的详细信息
    // shouldAnimate: true, // 运动状态
    //设置地形
    terrainProvider: Cesium.createWorldTerrain({
      requestWaterMask: true, // 水纹效果  海里面有波浪的效果
      requestVertextNormal: true, // 光照效果
    }),
  });

  // 设置 沙箱允许使用js
  /**
sandbox属性的值是一组空格分隔的标记，它们可以控制iframe中的内容具有哪些权限：

allow-same-origin：如果没有这个标记，页面会被当作从一个唯一的源加载的，无论它的实际来源或位置。这个标记使得页面可以脚本化同源的文档，并且允许存储cookies和localStorage。
allow-scripts：允许脚本（JavaScript）执行。如果没有这个标记，即使脚本被包含在页面中也不会执行。
allow-popups：允许弹出窗口，例如通过window.open方法。
allow-forms：允许表单提交。
   */
  var iframe = document.getElementsByClassName('cesium-infoBox-iframe')[0];
  iframe.setAttribute(
    'sandbox',
    'allow-same-origin allow-scripts allow-popups allow-forms'
  );
  iframe.setAttribute('src', '');

  //隐藏cesium Icon-logo
  viewer.cesiumWidget.creditContainer.style.display = 'none';

  // 3d建筑
  const tiles3d = Cesium.createOsmBuildings();
  const osmBuildings = viewer.scene.primitives.add(tiles3d);

  // 广州塔
  const positon = Cesium.Cartesian3.fromDegrees(113.3191, 23.109, 1000);

  viewer.camera.setView({
    destination: positon,
    // duration: 2,
    orientation: {
      heading: Cesium.Math.toRadians(0), // 方向
      pitch: Cesium.Math.toRadians(-40), // 倾斜角度，负值表示向下倾斜
      roll: 0.0, // 翻滚角度
    },
  });

  // 自定义设置建筑的样式 api https://cesium.com/learn/cesiumjs/ref-doc/Cesium3DTileStyle.html?classFilter=Cesium3DTileStyle
  // tiles3d.style = new Cesium.Cesium3DTileStyle({
  //   // color: "color('yellow')",
  //   color: 'rgba(255,255,0,0.5)',
  //   show: true,
  // });

  // https://blog.csdn.net/luoyun620/article/details/107572117
  tiles3d.style = new Cesium.Cesium3DTileStyle({
    defines: {
      distance:
        "distance(vec2(${feature['cesium#longitude']},${feature['cesium#latitude']}), vec2(113.3191, 23.109))",
    },
    color: {
      conditions: [
        ['${distance} < 0.01', "color('red')"],
        ['${distance} < 0.02', "color('yellow')"],
        ['${distance} < 0.04', "color('blue')"],
        ['true', "color('green')"],
      ],
    },
    show: '${distance} < 1',
  });
  addListener();

  function addListener() {
    var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    handler.setInputAction(function (click) {
      console.log('click: ' + click);
      // debugger;
      // setColor()
      var pickedFeature = viewer.scene.pick(click.position);
      console.log('pickedFeature=', pickedFeature);
      if (pickedFeature) {
        selectFeature(pickedFeature);
        // getAllProperty(pickedFeature);
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  }
  function selectFeature(feature) {
    console.log('feature:', feature, feature['name']);
    var selectbuilding = feature.getProperty('building');
    var s = "${feature['building']}";
    // var s = "${feature['building']} ===" + selectbuilding;
    console.log('s=', s, selectbuilding);
    var selectcontent = s;
    var transparentStyle = new Cesium.Cesium3DTileStyle({
      color: {
        conditions: [
          // [selectcontent, 'rgb(255,255,0)'],
          [
            "${feature['building']} === ${selectbuilding}",
            'rgba(45, 0, 75, 0.5)',
          ],
          // [
          //   "${feature['cesium#estimatedHeight']} < 300 && ${feature['building']} === ${selectbuilding}",
          //   'rgba(45, 0, 75, 0.5)',
          // ],
          // ['${height} >= 200', 'rgb(102, 71, 151)'],
          // ['${height} >= 100', 'rgb(170, 162, 204)'],
          // ['${height} >= 50', 'rgb(224, 226, 238)'],
          // ['${height} >= 25', 'rgb(252, 230, 200)'],
          // ['${height} >= 10', 'rgb(248, 176, 87)'],
          // ['${height} >= 5', 'rgb(198, 106, 11)'],
          ['true', 'rgb(127, 59, 8)'], // true表示剩余的显示的对象
        ],
      },
    });
    tiles3d.style = transparentStyle;
  }

  function getAllProperty(feature) {
    var propertyNames = feature.getPropertyNames();
    console.log(999, feature.getProperty('name'));
    var length = propertyNames.length;
    for (var i = 0; i < length; ++i) {
      var propertyName = propertyNames[i];
      if (feature.getProperty(propertyName)) {
        console.log(propertyName + ': ' + feature.getProperty(propertyName));
      }
    }
  }
});
</script>

<style scoped>
* {
  padding: 0;
  margin: 0;
}
#container {
  height: 94vh;
  width: 94vw;
}
</style>
